# app/modules/add_article.py
from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from werkzeug.utils import secure_filename
import os

from common import response_message
from model.article import Article

add_article = Blueprint('add_article', __name__)

# 配置上传文件夹和允许的文件类型
UPLOAD_FOLDER = 'resource/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

# 确保上传文件夹存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


# 检查文件扩展名是否允许
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@add_article.route('/add_article', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        # 处理表单提交
        title = request.form.get('title')
        content = request.form.get('article_content')
        tags = request.form.get('article_tag')
        article_type = request.form.get('article_type')

        # 处理上传的图片
        image_url = None
        if 'article_image' in request.files:
            file = request.files['article_image']
            print(file)
            if file.filename != '' and allowed_file(file.filename):
                picturename = os.path.splitext(file.filename)[0]
                filename = f"{picturename}.jpg"
                print(filename)
                secure_name = secure_filename(filename)
                print(secure_name)
                file_path = os.path.join(UPLOAD_FOLDER, filename)
                print(file_path)
                file.save(file_path)
                image_url = url_for('static', filename=f'uploads/{filename}')

        # 这里可以添加数据库保存逻辑
        article=Article()
        article.add_article(
        article_image=filename,
        title=title,
        article_content=content,
        article_tag=tags,
        article_type=article_type,

        )
        print(article)
        # 返回成功消息

        return jsonify({
            'success': True,
            'message': '文章已成功发布',
            'data': {
                'title': title,
                'content': content,
                'tags': tags,
                'article_type': article_type,
                'image_url': image_url
            }
        })

    # GET请求返回表单页面
    return render_template("add_article.html")
